package com.iflytek.jzcpx.procuracy.cont.service.impl;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.jzcpx.procuracy.common.model.HandContResult;
import com.iflytek.jzcpx.procuracy.common.model.HandContResultInfo;
import com.iflytek.jzcpx.procuracy.common.model.HandContResultInfoJzml;
import com.iflytek.jzcpx.procuracy.common.model.HandContResultInfoJzmlwj;
import com.iflytek.jzcpx.procuracy.common.util.JSONUtil;
import com.iflytek.jzcpx.procuracy.cont.model.JZML;
import com.iflytek.jzcpx.procuracy.cont.model.JZMLWJ;
import com.iflytek.jzcpx.procuracy.cont.model.SuccessJsonResult;
import com.iflytek.jzcpx.procuracy.cont.service.ContService;
import com.iflytek.jzcpx.procuracy.cont.vo.HandContModel;
import com.iflytek.jzcpx.procuracy.tools.csb.CsbUtil;
import com.iflytek.jzcpx.procuracy.tools.roma.RomaUtil;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class ContServiceImpl implements ContService {

    private static final Logger logger = LoggerFactory.getLogger(ContServiceImpl.class);

    /**
     *
     */
    @Value("${csb.enabled}")
    private boolean isCsb;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${swx.server.ip}")
    private String swxServerIp;

    @Value("${swx.server.cont.jzmlwj.api}")
    private String swx_dzmlwjUrl;

    @Value("${swx.server.cont.jzmlwj.jpg.api}")
    private String swx_dzmlwjJpgUrl;

    @Value("${swx.server.cont.jzmlwj.save.api}")
    private String swx_dzmlSaveUrl;
    
    @Value("${swx.server.cont.dzjzzz.save.api}")
    private String swx_dzjzzzSaveUrl;

    @Value("${skynet.ocr.path}")
    private String ocrEngineRest;

    /**
     * 获取卷宗目录
     */
    @Value("${swx.server.cont.dzjz.znbmdzjzmlwj.api}")
    private String contZnbmwjmlUrl;

    @Value("${skynet.ocr.server}")
    private String ocrEngineServer;

    @Autowired
    private CsbUtil csbUtil;
    @Autowired
    private RomaUtil romaUtil;
    @Value("${roma.enabled}")
    private boolean useHwApi;

    // ocr识别引擎配置

    @Override
    public String getDZJZInfo(String bsbh) {

        JSONObject object = new JSONObject();
        object.put("bsbh", bsbh);
        String url = swxServerIp + swx_dzmlwjUrl;
        String result = "";
        try {
            String bodyStr = object.toString();
            logger.debug("获取电子卷宗目录文件访问地址：{}，输入参数： {}", url, bodyStr);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Accept", "*/*");
            headers.add("systemid", "");
            headers.add("dzjz_token", "");
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> formEntity = new HttpEntity<String>(object.toString(), headers);

            if (isCsb) {
                result = csbUtil.doPostCsbApiNameContJzmlwj(bodyStr);
            }else if(useHwApi) {
            	result= romaUtil.doPostRomaApiNameContJzmlwj(bodyStr);
            }else {
                result = restTemplate.postForObject(url, formEntity, String.class);
            }

            logger.debug("获取电子卷宗目录文件接口返回结果：{}", result);
        } catch (Exception ex) {
            logger.warn("获取电子卷宗目录文件接口异常", ex);
        }
        return result;
    }


    /**
     * @param bsbh
     * @param wjxh
     * @return
     */
    @Override
    public byte[] getFileBytes(String bsbh, String wjxh) {

        JSONObject object = new JSONObject();
        object.put("bsbh", bsbh);
        object.put("wjxh", wjxh);
        String url = swxServerIp + swx_dzmlwjJpgUrl;
        byte[] dataBytes = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Accept", "*/*");
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> formEntity = new HttpEntity<String>(object.toString(), headers);

            String bodyStr = object.toString();
            logger.debug("请求电子卷宗JPG文件接口访问地址：{}，输入参数： {}", url, bodyStr);

            if (isCsb) {
                dataBytes = csbUtil.doPostCsbApiNameContJzmlwjJpg(bodyStr).getBytes();
            }else if(useHwApi) {
            	dataBytes= romaUtil.doPostRomaApiNameContJzmlwjJpg(bodyStr).getBytes();
            } else {
                ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.POST, formEntity, byte[].class);
                dataBytes = response.getBody();
            }

            if (dataBytes == null || dataBytes.length <= 500) {
                logger.debug("请求电子卷宗JPG文件接口访问失败，未获取到文件流");
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return dataBytes;
    }

    /**
     * 获取赛威讯的文件字节流
     */
    @Override
    public byte[] getFileBytesBySWX(String bsbh, String wjxh) {
        byte[] dataBytes = getFileBytes(bsbh, wjxh);

        byte[] b1 = new byte[dataBytes.length - 300];
        System.arraycopy(dataBytes, 300, b1, 0, dataBytes.length - 300);
        dataBytes = null;

        return b1;
    }

    /**
     *
     */
    @Override
    public String SaveDZJZInfo(String body) {
        String url = swxServerIp + swx_dzmlSaveUrl;
        String result = "";
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Accept", "*/*");
            headers.add("systemid", "");
            headers.add("dzjz_token", "");
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> formEntity = new HttpEntity<String>(body, headers);


            logger.debug("提交电子卷宗编目结果接口访问地址：{}，输入参数： {}", url, body);

            if (isCsb) {
                result = csbUtil.doPostCsbApiNameContJzmlwjSave(body);
            }else if(useHwApi) {
            	result= romaUtil.doPostRomaApiNameContJzmlwjSave(body);
            } else {
                result = restTemplate.postForObject(url, formEntity, String.class);
            }
            logger.debug("提交电子卷宗编目结果接口返回结果 {}", result);

        } catch (Exception ex) {
            logger.warn("提交电子卷宗编目结果接口异常", ex);
        }
        return result;
    }
    
    /**
    *
    */
   @Override
   public String saveDzjzzzInfo(String body) {
       String url = swxServerIp + swx_dzjzzzSaveUrl;
       String result = "";
       try {
           HttpHeaders headers = new HttpHeaders();
           headers.add("Accept", "*/*");
           headers.add("systemid", "");
           headers.add("dzjz_token", "");
           headers.setContentType(MediaType.APPLICATION_JSON);
           HttpEntity<String> formEntity = new HttpEntity<String>(body, headers);


           logger.debug("提交3.2.8	接口8：提交电子卷宗编目结果记录（api-08）接口访问地址：{}，输入参数： {}", url, body);

           if (isCsb) {
               result = csbUtil.doPostCsbApiNameContJzmlwjSave(body);
           }else if(useHwApi) {
           	result= romaUtil.doPostRomaApiNameContJzmlwjSave(body);
           } else {
               result = restTemplate.postForObject(url, formEntity, String.class);
           }
           logger.debug("提交3.2.8	接口8：提交电子卷宗编目结果记录（api-08）接口返回结果 {}", result);

       } catch (Exception ex) {
           logger.warn("提交3.2.8	接口8：提交电子卷宗编目结果记录（api-08）接口异常", ex);
       }
       return result;
   }

    /**
     *
     */
    @Override
    public String recognize(String bsbh, String wjxh) {

        byte[] fileBytes = getFileBytesBySWX(bsbh, wjxh);

        JSONObject ocrParams = new JSONObject();
        ocrParams.put("pagetype", "page");
        ocrParams.put("resultlevel", "3");
        ocrParams.put("funclist", "ocr,er");

        Path file = null;
        UUID uuid = UUID.randomUUID();
        String fileName = uuid.toString();
        try {
            file = Files.createTempFile(fileName, ".jpg");
            FileUtils.writeByteArrayToFile(file.toFile(), fileBytes);

            // 应用退出时删除文件, 兜底
            file.toFile().deleteOnExit();

            String resultStr = recognize(file.toFile(), ocrParams, fileName);
            return resultStr;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (file.toFile() != null) {
                // 删除临时文件
                FileUtils.deleteQuietly(file.toFile());
            }
        }
    }

    /**
     * @param file
     * @param trackId
     * @return
     */
    @Override
    public String recognize(File file, JSONObject params, String trackId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        FileSystemResource resource = new FileSystemResource(file);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("picFile", resource);
        String url = ocrEngineServer + ocrEngineRest.replace("{trackId}", trackId);
        url = url + "?params={params}";

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
        String result = "";
        try {
            result = restTemplate.postForObject(url, httpEntity, String.class, params.toJSONString());
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        try {
            result = JSONUtil.getProp(JSONUtil.toJsonNode(result), "body", String.class);
        } catch (Exception ex) {

        }

        return result;
    }

    /**
     * @param handContModel
     * @return
     */
    @Override
    public SuccessJsonResult<Void> handCont(HandContModel handContModel) {
        return null;
    }

    /**
     * @param handContResultInfoJzml
     * @return
     */
    public List<JZML> handContJzml2Jzml(HandContResultInfoJzml handContResultInfoJzml) {
        List<JZML> jzmls = new ArrayList<>();
        JZML jzml = JSON.parseObject(JSONObject.toJSONString(handContResultInfoJzml), JZML.class);
        jzmls.add(jzml);
        return jzmls;
    }

    /**
     * @param handContResultInfoJzmlwjs
     * @return
     */
    public List<JZMLWJ> HandContJzmlwj(List<HandContResultInfoJzmlwj> handContResultInfoJzmlwjs) {
        List<JZMLWJ> jzmlwjs = new ArrayList<>();

        Iterator iterator = handContResultInfoJzmlwjs.iterator();
        while (iterator.hasNext()) {
            HandContResultInfoJzmlwj handContResultInfoJzmlwj = (HandContResultInfoJzmlwj) iterator.next();
            JZMLWJ jzmlwj = JSON.parseObject(JSONObject.toJSONString(handContResultInfoJzmlwj), JZMLWJ.class);

            jzmlwjs.add(jzmlwj);
        }
        return jzmlwjs;
    }

    /**
     * @param jzbh
     * @param mlbh
     * @return
     */
    public HandContResultInfo getContDataFromSwx(String jzbh, String mlbh) {
        HandContResult handContResult = new HandContResult();
        //HandContResultInfo handContResultInfo=new HandContResultInfo();
        JSONObject object = new JSONObject();
        object.put("jzbh", jzbh);
        object.put("mlbh", mlbh);
        String url = swxServerIp + contZnbmwjmlUrl;
        byte[] dataBytes = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Accept", "*/*");
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> formEntity = new HttpEntity<String>(object.toString(), headers);

            String bodyStr = object.toString();
            logger.debug("访问地址：{}，输入参数： {}", url, bodyStr);

            if (isCsb) {
                //dataBytes=csbUtil.doPostCsbApiNameContJzmlwjJpg(bodyStr).getBytes();
            }else if(useHwApi) {
            	//dataBytes=romUtil.doPostCsbApiNameContJzmlwjJpg(bodyStr).getBytes();
            } else {
                ResponseEntity<HandContResult> response = restTemplate.exchange(url, HttpMethod.POST, formEntity, HandContResult.class);
                handContResult = response.getBody();
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return handContResult.getData();
    }
}
